package hub

import (
	"FeedXmh/app/dao"
	"FeedXmh/redis"
	"fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
	"paco_toolkit/common"
)

func ClearFeedRecords() {
	expired_date := gtime.Now().AddDate(0, -2, 0).Format(common.DATE_FORMAT)
	g.Log().Line(true).Infof("ClearFeedRecords expired_date = %s", expired_date)
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	sql := fmt.Sprintf(`DELETE FROM t_hzfgw_record WHERE rectime<'%s'`, expired_date)
	res, err := db.Exec(sql)
	if err != nil {
		g.Log().Line(true).Error(err)
		return
	}
	aff, _ := res.RowsAffected()
	g.Log().Line(true).Infof("ClearFeedRecords OK, RowsAffected=%d", aff)

	g.Log().Line(true).Info("OPTIMIZE TABLE t_hzfgw_record")
	sql = "OPTIMIZE TABLE t_hzfgw_record"
	res, err = db.Exec(sql)
	if err != nil {
		g.Log().Line(true).Error(err)
		return
	}
	g.Log().Line(true).Info("OPTIMIZE TABLE t_hzfgw_record OK")
}

func CheckNodeOffline() {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	sql := fmt.Sprintf("SELECT * FROM t_alarm WHERE `status`=1 AND device_type='NMSWQGW_NODE' AND alarm_content='饲喂器离线';")
	res, err := db.GetAll(sql)
	if err != nil {
		g.Log().Line(true).Error(err)
		return
	}
	items := res.List()
	if len(items) > 0 {
		for _, item := range items {
			addr := gconv.String(item["device_addr"])
			sn := gconv.String(item["sn"])
			alive := redis.GetGwNodeAlive(addr, sn)
			//g.Log().Line(true).Debugf(" check sn=%s idx=%d", sn, key)
			if alive {
				_, err := dao.T_alarm.CancelAlarm(gconv.String(item["id"]), "")
				if err != nil {
					g.Log().Line(true).Error(err)
				} else {
					g.Log().Line(true).Debugf("addr=%s sn=%s 消除离线告警", addr, sn)
				}
			}
		}
	}

	g.Log().Line(true).Info("CheckNodeOffline done!")
}

func UpdateFeedPlanGroupCode() {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	sql := fmt.Sprintf("SELECT * FROM t_feed_plan_new WHERE IFNULL(farmid,0)!=0;")
	res, err := db.GetAll(sql)
	if err != nil {
		g.Log().Line(true).Error(err)
		return
	}

	sql1 := fmt.Sprintf("SELECT * FROM v_farm")
	res1, err1 := db.GetAll(sql1)
	if err1 != nil {
		g.Log().Line(true).Error(err1)
		return
	}

	items := res.List()
	farms := res1.List()
	if len(items) > 0 {
		for _, item := range items {
			farmid := gconv.String(item["farmid"])
			for _, farm := range farms {
				if farmid == gconv.String(farm["id"]) {
					item["group_code"] = gconv.String(farm["group_code"])
					_, err := dao.T_feed_plan_new.Save(item)
					if err != nil {
						g.Log().Line(true).Error(err)
					} else {
						g.Log().Line(true).Debugf("update farmid=%s feed_plan_new group_code=%s", farmid, gconv.String(farm["group_code"]))
					}
					break
				}
			}
		}
	}
}
